package com.yozinga.fragment;

import java.lang.reflect.InvocationTargetException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.yozinga.R;
import com.yozinga.entity.Category;
import com.yozinga.model.AboutYozingaModel;
import com.yozinga.model.BaseModel.OnRequestFinishedCallback;
import com.yozinga.processor.AboutYozingaProcessor;
import com.yozinga.service.Actions;
import com.yozinga.util.AppData;
import com.yozinga.util.NativeAppInvoker;
import com.yozinga.util.ToolKit;

public class AboutFragment extends BaseFragment implements OnRequestFinishedCallback,OnClickListener{
	Category mCategory;
	TextView mAddress,mPhone,mInfo;
	VideoView mVideoView;
	AboutYozingaModel aboutModel;

	GoogleMap map;
	ArrayList<LatLng> markerPoints;
	MediaController mc ;
	ProgressDialog pb;
	WebView mWebView;
	String faceBookUrl,twitterUrl,number;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_about, container,false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		Button saveButton = (Button) getActivity().findViewById(R.id.save);
		saveButton.setVisibility(View.GONE);
		
		ToolKit.startProgress(getActivity(), R.string.loading);
		aboutModel = new AboutYozingaModel(getActivity());
		aboutModel.addOnServiceRequestCompletedListener(this);
		aboutModel.getYozingaInfo(AppData.GET_ABOUT_YOZINGA, Actions.ACTION_GET_ABOUT_YOZINGA);

		mAddress = (TextView)getView().findViewById(R.id.tvAddress);
		mPhone = (TextView)getView().findViewById(R.id.tvPhone);
		mPhone.setOnClickListener(this);
		
		mInfo = (TextView)getView().findViewById(R.id.tvInfo);

		ImageView ivFaceBook = (ImageView)getView().findViewById(R.id.ivFacebook);
		ivFaceBook.setOnClickListener(this);

		ImageView ivTwitter = (ImageView)getView().findViewById(R.id.ivTwitter);
		ivTwitter.setOnClickListener(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		aboutModel.removeOnServiceRequestCompleteListener(this);
		Log.i("Today","On Pause");
		try {
			if(mWebView!=null){
				Class.forName("android.webkit.WebView").getMethod("onPause", (Class[]) null).invoke(mWebView, (Object[]) null);
			}
		} catch(ClassNotFoundException cnfe) {
		} catch(NoSuchMethodException nsme) {
		} catch(InvocationTargetException ite) {
		} catch (IllegalAccessException iae) {
		}
	}

	@Override
	public void onRequestFinished(int resultCode, Bundle payload) {
		String response = payload.getString("ServiceResponse");
		Log.i("Today","GET_ABOUT_YOZINGA Respons is :"+response);
		AboutYozingaProcessor aboutYozingaProcessor = new AboutYozingaProcessor();
		mCategory = aboutYozingaProcessor.getYozingaInfo(response);

		ToolKit.stopprogess();

		mAddress.setText(mCategory.getStreetAddress());
		mPhone.setText(mCategory.getPhoneNumber());
		mInfo.setText(mCategory.getInfo());

		number = mCategory.getPhoneNumber();
		String videoUrl = mCategory.getVideoUrl();
		faceBookUrl = mCategory.getFaceBookUrl();
		twitterUrl = mCategory.getTwitterUrl();

		//TO Play 3gp Videos	
		/*String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp";
		mVideoView = (VideoView)getView().findViewById(R.id.vvVideo);
		mVideoView.setVideoURI(Uri.parse(SrcPath));
		mVideoView.setMediaController(new MediaController(getActivity()));
		mVideoView.requestFocus();
		mVideoView.start();*/


		//TO Play WebView videos
		mWebView = (WebView) getView().findViewById(R.id.vvVideo);
		getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE) ; 
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().getJavaScriptCanOpenWindowsAutomatically();
		//mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
		//mWebView.getSettings().setPluginState(PluginState.ON);
		try {
			mWebView.loadUrl("http://www.youtube.com/embed/" +  extractYoutubeId(videoUrl)
					+ "?autoplay=1&vq=small");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mWebView.setWebChromeClient(new WebChromeClient());

		//TO Play viewView Videos
		/*mc = new MediaController(getActivity());
		pb = new ProgressDialog(getActivity());
		LongOperation lg = new LongOperation();
		lg.execute();*/
	}

	private class LongOperation extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			return getUrlVideoRTSP("");
		}      

		@Override
		protected void onPostExecute(String result) {
			//pb.dismiss();
			VideoView video = (VideoView)getView().findViewById(R.id.vvVideo);
			DisplayMetrics metrics = new DisplayMetrics(); 
			getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
			android.widget.FrameLayout.LayoutParams params = (android.widget.FrameLayout.LayoutParams) video.getLayoutParams();
			params.width =  metrics.widthPixels;
			params.height = metrics.heightPixels;
			params.leftMargin = 0;

			Log.i("Team","Youtube Url is: "+getUrlVideoRTSP(""));
			video.setVideoURI(Uri.parse(result));
			video.setLayoutParams(params);

			video.setMediaController(mc);
			video.requestFocus();
			video.start();  

			mc.show();    }

		@Override
		protected void onPreExecute() {

			//pb.show();
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}   

	public static String getUrlVideoRTSP(String urlYoutube)
	{
		try
		{
			String gdy = "http://gdata.youtube.com/feeds/api/videos/";
			DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			String id = extractYoutubeId("http://www.youtube.com/watch?v=uIDx3eUZ-vw");
			URL url = new URL(gdy + id);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			Document doc = documentBuilder.parse(connection.getInputStream());
			org.w3c.dom.Element el =  doc.getDocumentElement();
			NodeList list =  el.getElementsByTagName("media:content");///media:content
			String cursor = urlYoutube;
			for (int i = 0; i < list.getLength(); i++)
			{
				Node node = list.item(i);
				if (node != null)
				{
					NamedNodeMap nodeMap = node.getAttributes();
					HashMap<String, String> maps = new HashMap<String, String>();
					for (int j = 0; j < nodeMap.getLength(); j++)
					{
						Attr att = (Attr) nodeMap.item(j);
						maps.put(att.getName(), att.getValue());
					}
					if (maps.containsKey("yt:format"))
					{
						String f = maps.get("yt:format");
						if (maps.containsKey("url"))
						{
							cursor = maps.get("url");
						}
						if (f.equals("1"))
							return cursor;
					}
				}
			}
			return cursor;
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			Log.e("Team","Exception"+ ex.toString());
		}
		return urlYoutube;

	}


	protected static String extractYoutubeId(String url) throws MalformedURLException
	{
		String id = null;
		try
		{
			String query = new URL(url).getQuery();
			if (query != null)
			{
				String[] param = query.split("&");
				for (String row : param)
				{
					String[] param1 = row.split("=");
					if (param1[0].equals("v"))
					{
						id = param1[1];
					}
				}
			}
			else
			{
				if (url.contains("embed"))
				{
					id = url.substring(url.lastIndexOf("/") + 1);
				}
			}
		}
		catch (Exception ex)
		{
			Log.e("Exception", ex.toString());
		}
		return id;
	}

	@Override
	public void onClick(View v) {
		NativeAppInvoker nativeAppInvoker = new NativeAppInvoker(getActivity());
		if(v.getId() ==  R.id.ivFacebook){
			nativeAppInvoker.browserInvoker(faceBookUrl);
		}else if(v.getId() == R.id.ivTwitter){
			nativeAppInvoker.browserInvoker(twitterUrl);
		}else if(v.getId() ==  R.id.tvPhone){
			nativeAppInvoker.dialPadInvoker(number);
		}
	}

}
